import { FakeApi, random } from '@wowon/utils';
import { userList } from '../access/user';
import { fileList } from './file';
import { getCurrentUser } from '../../auth-center';

const titles = ['12306上线“同车换乘”功能', '全国春灌有序展开', '8天打5虎 官方：铁面反腐不慈悲', '每天睡多久才算睡够了'];

const content =
  'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.';

const initConent = () => ({
  title: random(titles),
  cover: fileList.pick({ name: 'cover' }),
  star: random(100, 200000),
  like: random(200, 3000000),
  comment: random(0, 10000),
  resume: 'Ant Design, a design language for background applications, is refined by Ant UED Team.',
  content,
  fragment: content.substring(0, 150),
});

const initData = Array.from({ length: random(50, 200) }).map((_, i) => {
  const author = userList.pick();
  return {
    ...initConent(),
    author_id: author.id,
    author,
  };
});

export const noticeList = new FakeApi(initData, {
  queryType: {
    id: 'is',
    title: 'like',
    author_id: 'is',
  },
});

export default {
  'GET /mock/notice/query': async (req, res) => {
    const currentUser = getCurrentUser(req);
    if (!currentUser) {
      res.statusCode = 401;
      res.json({ code: '-1', message: '权限不足' });
      return;
    }
    const result = await noticeList.query(req.query);
    res.json(result);
  },
  'POST /mock/notice/create': async (req, res) => {
    const currentUser = getCurrentUser(req);
    if (!currentUser) {
      res.statusCode = 401;
      res.json({ code: '-1', message: '权限不足' });
      return;
    }
    const author = currentUser.data;
    const article = {
      ...initConent(),
      ...req.body,
      author_id: author.id,
      author,
    };
    const result = await noticeList.create(article);
    res.json(result);
  },
  'POST /mock/notice/update': async (req, res) => {
    const currentUser = getCurrentUser(req);
    if (!currentUser) {
      res.statusCode = 401;
      res.json({ code: '-1', message: '权限不足' });
      return;
    }
    const author = currentUser.data;
    const article = {
      ...initConent(),
      ...req.body,
      author_id: author.id,
      author,
    };
    const result = await noticeList.update(article);
    res.json(result);
  },
  'POST /mock/notice/remove': async (req, res) => {
    const currentUser = getCurrentUser(req);
    if (!currentUser) {
      res.statusCode = 401;
      res.json({ code: '-1', message: '权限不足' });
      return;
    }
    const result = await noticeList.remove(req.body);
    res.json(result);
  },
  /** 详情 */
  'GET /mock/notice/profile': async (req, res) => {
    const currentUser = getCurrentUser(req);
    if (!currentUser) {
      res.statusCode = 401;
      res.json({ code: '-1', message: '权限不足' });
      return;
    }
    const result = await noticeList.profile(req.query);
    res.json(result);
  },
};
